import 'dart:convert';

import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

import 'common/models.dart';

class AdressListPage extends StatefulWidget {
  @override
  _AdressListPageState createState() => _AdressListPageState();
}

class _AdressListPageState extends State<AdressListPage> {
  final ItemScrollController itemScrollController = ItemScrollController();
  final ItemPositionsListener itemPositionsListener =
      ItemPositionsListener.create();
  List<ContactInfo> _contacts = [];
  double susItemHeight = 40;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    itemPositionsListener.itemPositions.addListener(() {
      print('object');
    });
    loadData();
  }

  void loadData() async {
    //加载联系人列表
    rootBundle.loadString('assets/data/contacts.json').then((value) {
      List list = json.decode(value);
      list.forEach((v) {
        _contacts.add(ContactInfo.fromJson(v));
      });
      _handleList(_contacts);
    });
  }

  ///添加多音字 拼音可百度
  void addDist() {
    PinyinHelper.addMultiPinyinDict(
        ['厦门=xià,mén', '重庆=chóng,qìng', '重卡=zhòng,kǎ', '长大=zhǎng,dà']);
  }

  void _handleList(List<ContactInfo> list) {
    if (list == null || list.isEmpty) return;
    addDist();
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(_contacts);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(_contacts);

    // add header.
    _contacts.insert(0, ContactInfo(name: 'header', tagIndex: '↑'));

    setState(() {});
  }

  Decoration getIndexBarDecoration(Color color) {
    return BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(20.0),
        border: Border.all(color: Colors.grey[300], width: .5));
  }

  Widget _buildSusWidget(String susTag) {
    return Container(
      padding: EdgeInsets.only(right: 16.0),
      height: susItemHeight,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      child: Row(
        children: <Widget>[
          Expanded(
              child: Container(
            padding: EdgeInsets.only(left: 16, top: 2, bottom: 2),
            child: Text(
              '$susTag',
              textScaleFactor: 1.2,
            ),
            decoration: BoxDecoration(
              color: Color.fromRGBO(0, 0, 0, 0.12),
            ),
          ))
          // Text(
          //   '$susTag',
          //   textScaleFactor: 1.2,
          // ),
          // Expanded(
          //     child: Divider(
          //   height: .0,
          //   indent: 10.0,
          // ))
        ],
      ),
    );
  }

  Widget _buildListItem(ContactInfo model) {
    String susTag = model.getSuspensionTag();
    return Column(
      children: <Widget>[
        Offstage(
          offstage: model.isShowSuspension != true,
          child: _buildSusWidget(susTag),
        ),
        ListTile(
          leading: CircleAvatar(
            backgroundColor: Colors.blue[700],
            child: Text(
              model.name[0],
              style: TextStyle(color: Colors.white),
            ),
          ),
          title: Text(model.name),
          subtitle: Text(model.nickName),
          onTap: () {
            print("OnItemClick: $model");
            Navigator.pop(context, model);
          },
        ),
      ],
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.all(20),
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ListTile(
            leading: Text('icon图'),
            title: Text('新的朋友'),
            onTap: () {
              print('_前往新页面');
            },
          ),
          Divider(),
          ListTile(
            leading: Text('icon图'),
            title: Text('群聊'),
            onTap: () {
              print('_前往新页面');
            },
          ),
          Divider(),
          ListTile(
            leading: Text('icon图'),
            title: Text('生活号'),
            onTap: () {
              print('_前往新页面');
            },
          ),
          Divider(),
          ListTile(
            leading: Text('icon图'),
            title: Text('生活圈'),
            onTap: () {
              print('_前往新页面');
            },
          ),
          Divider(),
          ListTile(
            leading: Text('icon图'),
            title: Text('转账名片夹'),
            onTap: () {
              print('_前往新页面');
            },
          ),
        ],
      ),
    );
  }

  Widget buildAzListView(BuildContext context) {
    return AzListView(
      data: _contacts,
      itemCount: _contacts.length,
      itemBuilder: (BuildContext context, int index) {
        if (index == 0) return _buildHeader();
        ContactInfo model = _contacts[index];
        return _buildListItem(model);
      },
      physics: BouncingScrollPhysics(),
      indexBarData: SuspensionUtil.getTagIndexList(_contacts),
      indexHintBuilder: (context, hint) {
        return Container(
          alignment: Alignment.center,
          width: 60.0,
          height: 60.0,
          decoration: BoxDecoration(
            color: Colors.blue[700].withAlpha(200),
            shape: BoxShape.circle,
          ),
          child:
              Text(hint, style: TextStyle(color: Colors.white, fontSize: 30.0)),
        );
      },
      indexBarMargin: EdgeInsets.all(10),
      indexBarOptions: IndexBarOptions(
        needRebuild: true,
        decoration: getIndexBarDecoration(Colors.grey[50]),
        downDecoration: getIndexBarDecoration(Colors.grey[200]),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('通讯录'),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: Icon(IconData(0xe607, fontFamily: 'iconfont')),
          ),
          IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: Icon(IconData(0xe61e, fontFamily: 'iconfont')),
          )
        ],
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: Icon(IconData(0xe624, fontFamily: 'iconfont')),
        ),
      ),
      body: buildAzListView(context),
    );
  }
}
